<template>
  <div class="applicationDetail">
    <div class="title-box"><span>实例规格组</span><span class="back return" @click="goback">&lt;&nbsp;返回</span></div>
    <div class="details">
      <div class="title">实例规格名称&nbsp;{{ details.data.name }}&nbsp;详情</div>
      <el-form ref="table">
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in basic" :key="key">
            <div class="content-label">{{ item }}</div>
            <div v-if="key == 'creation_time' || key == 'id' || key == 'update_time' || key == 'resource_specification' || key == 'name'" class="content-text">
              <div>{{ details.data[key] ? details.data[key] : '--' }}</div>
            </div>
          </div>
        </div>
        <div class="securityGroup">
          <div class="securityNames">规格列表</div>
          <div class="singleGroup">
            <span class="adaptive" v-for="item in details.data.flavor">{{ item ? item + `&nbsp; ` : '--' }}</span>
          </div>
        </div>
      </el-form>
    </div>
    <div class="details">
      <div class="title">已关联Fleet</div>
      <div class="app-table">
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }" :border="true">
          <el-table-column label="Fleet名称/ID" class-name="elcell" width="260">
            <template #default="scope">
              <div class="toDetails" @click="toFleetDetails(scope.row.fleet_id, scope.row.name)">
                {{ scope.row.name }}
              </div>
              <el-tooltip effect="dark" :content="scope.row.fleet_id" placement="bottom">
                <div class="id-box">
                  {{ scope.row.fleet_id }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态">
            <template #default="scope">
              {{ scope.row.state ? $t('alias.' + scope.row.state) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="instance_count" label="实例数量"> </el-table-column>
          <el-table-column prop="process_count" label="进程并发启动数量" />
          <el-table-column prop="max_server_session_count" label="进程最大会话数量" />
        </el-table>
      </div>
      <!-- 新建实例规格组弹框 -->
      <el-dialog title="修改实例规格" v-model="dialogVisible" width="600px" center>
        <div class="inputAll">
          <div class="inputSize">
            <el-input v-model="instanceInput" placeholder="请输入实例规格组名" :disabled="true" />
            <el-scrollbar>
              <div class="selected">已选实例规格：{{ selectedCount }}</div>
              <el-tree :data="selectedOptions" :props="defaultProps" :default-expand-all="true" />
            </el-scrollbar>
          </div>
          <div class="inputSize">
            <el-input v-model="filterText" @keyup.enter.native="filterInput" placeholder="请输入关键字进行搜索" :suffix-icon="Search" />
            <el-scrollbar>
              <el-tree
                ref="treeRef"
                :data="exampleOptions"
                show-checkbox
                :props="defaultProps"
                node-key="label"
                :filter-node-method="filterNode"
                :default-checked-keys="tableData1"
                @check="handleCheckChange"
              />
            </el-scrollbar>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="SureInstance()">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import appStore from '@/store'
  import { reactive, ref, nextTick, watch } from 'vue'
  import router from '@/router'
  import { useRoute } from 'vue-router'
  import UserService, { deleteList, instances } from '@/api/userService'
  import { timeFormathmsUTC } from '@/utils/formatter'
  import { ElMessage, FormInstance, ElMessageBox } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  const route = useRoute()
  const treeRef = ref(null) as any
  const dialogVisible = ref(false)
  const filterText = ref('')
  let exampleOptions = reactive([] as any[])
  let selectedOptions = reactive([] as any[])
  const instanceInput = ref('')
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  let buildApp: deleteList = {
    project_id: appStore.userStore.project_id,
    resource_specification_id: `${route.params.id}`
  }
  const defaultProps = {
    children: 'children',
    label: 'label'
  }
  watch(filterText, (val: any) => {
    treeRef.value!.filter(val)
  })
  const filterInput = () => {
    treeRef.value.filter(filterText)
  }
  const filterNode = (value: string, data: any, node: any) => {
    if (!value) {
      node.expanded = false
      return true
    }
    let val = value.toLowerCase()
    return chooseNode(val, data, node)
  }
  const chooseNode = (value: any, data: any, node: any) => {
    if (data.label.indexOf(value) !== -1) {
      return true
    }
    const level = node.level
    if (level === 1) {
      return false
    }
    let parentData = node.parent
    let index = 0
    while (index < level - 1) {
      if (parentData.data.label.indexOf(value) !== -1) {
        return true
      }
      parentData = parentData.parent
      index++
    }
    return false
  }
  const table = ref<FormInstance>()
  let details: { data: { [key: string]: string | { [key: string]: string } | { [key: string]: any } } } = reactive({
    data: {
      project_id: appStore.userStore.project_id,
      resource_specification_id: `${route.params.id}`,
      resource_specification: '',
      update_time: '',
      creation_time: '',
      flavor: [],
      name: '',
      region: appStore.userStore.region
    }
  })
  let tableData: Array<{ [key: string]: string }> = reactive([])
  let tableData1 = reactive([] as any[])
  const toDetails = async () => {
    let res = await UserService.detailsInstanceData(buildApp)
    if (res.status === 200) {
      details.data = res.data
      details.data.update_time = timeFormathmsUTC(details.data.update_time)
      details.data.creation_time = timeFormathmsUTC(details.data.creation_time)
      tableData.length = 0
      if (res.data.associated_fleets) {
        tableData.push(...res.data.associated_fleets)
      }
    }
  }

  const handleCheckChange = async (data: any, a: any) => {
    let newArr = reactive([] as any[])
    let isShow = a.checkedKeys.includes(data.value)
    let isLevel1 = !!data.children
    if (isLevel1) {
      if (isShow) {
        let children = reactive([] as any[])
        data.children.forEach((cItem: any) => {
          children.push(cItem)
        })
        newArr.push({
          label: data.label,
          value: data.value,
          children: children
        })
        let checkedKeys = [data.label, ...children.map((cItem) => cItem.label)]
        treeRef.value.setCheckedKeys(checkedKeys)
        selectedOptions.length = 0
        selectedOptions.push(...newArr)
      } else {
        treeRef.value.setCheckedKeys([])
        selectedOptions.length = 0
      }
    } else {
      let label = data.label
      let level1Arr = exampleOptions.filter((item) => {
        let childrenLabels = item.children.map((cItem: any) => cItem.label)
        return childrenLabels.includes(label)
      })
      let level1Item = level1Arr[0] || {}
      let curSelectedOption = selectedOptions[0] || {}
      let children = []
      if (curSelectedOption.label === level1Item.label) {
        if (isShow) {
          children = [...curSelectedOption.children, { label: data.label, value: data.value }]
        } else {
          children = curSelectedOption.children.filter((cItem: any) => cItem.label !== label)
        }
        if (children.length) {
          newArr.push({
            label: level1Item.label,
            value: level1Item.value,
            children: children
          })
        }
      } else {
        newArr.push({
          label: level1Item.label,
          value: level1Item.value,
          children: [{ label: data.label, value: data.value }]
        })
      }
      let checkedKeys = []
      if (newArr[0]) {
        if (newArr[0].children.length === level1Item.children.length) {
          checkedKeys = [level1Item.label, ...newArr[0].children.map((cItem: any) => cItem.label)]
        } else {
          checkedKeys = [newArr[0].children.map((cItem: any) => cItem.label)]
        }
        if (curSelectedOption.label === level1Item.label) {
          treeRef.value.setChecked(checkedKeys, true, true)
        } else {
          treeRef.value.setCheckedKeys(checkedKeys, false)
        }
      } else {
        treeRef.value.setCheckedKeys([])
      }
      if (newArr.length) {
        selectedOptions.length = 0
        selectedOptions.push(...newArr)
      } else {
        selectedOptions.length = 0
      }
    }
  }
  let selectedCount = ref(0)
  watch(selectedOptions, (val: any) => {
    val.forEach((itCem: any) => {
      selectedCount.value = itCem.children.length
      if (itCem.children && itCem.children.length > 10) {
        ElMessageBox.alert('实例规格列表最多可选择十条', '提示', {
          confirmButtonText: 'OK',
          callback: () => {}
        })
      }
    })
  })
  const getResourceSpecification = async () => {
    let res = await UserService.getResourceSpecification(getbucket)
    if (res.status == 200) {
      let object = res.data
      for (const key in object) {
        if (Object.prototype.hasOwnProperty.call(object, key)) {
          const element = object[key]
          let obj1 = { value: key, label: key, children: [] as any[] }
          exampleOptions.push(obj1)
          if (Array.isArray(element)) {
            element.forEach((item: any) => {
              obj1.children.push({
                value: item,
                label: item
              })
            })
          }
        }
      }
    }
  }
  let flavorData = reactive([] as any[])
  const SureInstance = async () => {
    let determineData = ''
    flavorData = []
    selectedOptions.forEach((item: any) => {
      determineData = item.label
      item.children.forEach((it: any) => {
        flavorData.push(it.label)
      })
    })
    if (flavorData.length > 10) {
      ElMessageBox.alert('实例规格列表最多可选择十条', '提示', {
        confirmButtonText: 'OK',
        callback: () => {}
      })
    } else {
      let absolutea = {
        name: details.data.name,
        id: details.data.id,
        resource_specification: determineData,
        project_id: appStore.userStore.project_id,
        region: appStore.userStore.region,
        flavor: flavorData,
        new_name: details.data.name
      }
      try {
        let res = await UserService.updataInstanceList(absolutea)
        if (res.status < 300) {
          details.data.resource_specification = determineData
          details.data.flavor = flavorData
          ElMessage({
            message: '修改成功',
            type: 'success'
          })
          dialogVisible.value = false
          toDetails()
        }
      } catch (err) {
        ElMessage.error('修改失败')
      }
    }
  }

  let getbucket: instances = reactive({
    name: '',
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    offset: 1,
    limit: 10,
    resource_specification: ''
  })

  const toFleetDetails = (id: string, name: string) => {
    router.push({ name: 'fleetDetails', params: { id, name } })
  }
  const goback = () => {
    router.push({
      name: 'instanceList'
    })
  }
  const basic = {
    name: '实例规格名称',
    creation_time: '创建时间',
    id: '实例规格ID',
    update_time: '修改时间',
    resource_specification: '实例规格'
  }
  toDetails()
</script>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  .applicationDetail {
    .title-box {
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 21px;
        line-height: 60px;
      }
      .return {
        margin-left: -11px;
        font-size: 14px;
      }
    }

    .details {
      .content-box {
        .content-text {
          width: auto;
          .el-form-item {
            margin-bottom: 0;
          }
        }
        .modify {
          margin-left: 50px;
          font-size: 14px;
          color: #325cb0;
          cursor: pointer;
        }
      }
    }
    .details:last-of-type {
      margin-top: 20px;
    }
    .app-table {
      :deep(.el-table) {
        border-radius: 2px;
        font-size: 14px;
        color: $text-color;
        tr {
          border-color: $border-color;
          height: 78px;
        }
        thead > tr:first-child {
          height: 36px;
        }
        .el-table__cell {
          border-right: none;
        }
      }
      :deep(.toDetails) {
        color: $main-color;
        cursor: pointer;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.toDetails:hover) {
        text-decoration: underline;
      }
      :deep(.id-box) {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.cell) {
        padding: 0 30px 0 20px;
      }
    }
    .securityGroup {
      display: flex;
      margin-bottom: 20px;
      .securityNames {
        color: #8a8e99;
        font-size: 14px;
      }
      .singleGroup {
        width: 500px;
        flex-direction: column;
        margin-left: 64px;
        height: auto;
        .adaptive {
          height: 26px;
          color: #252b3a;
          font-size: 14px;
        }
      }
    }
    .inputAll {
      display: flex;
      margin-bottom: -10px;
      .inputSize {
        width: 260px;
        margin-right: 20px;
        .selected {
          font-size: 14px;
          font-weight: Bold;
          color: #252b3a;
          margin-left: 10px;
          margin-top: 10px;
        }
      }
    }
    .el-tree {
      max-height: 450px;
      font-size: 14px;
    }
    .el-scrollbar {
      height: 450px;
      margin-top: 10px;
    }
    .dialog-footer .el-button {
      width: 120px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
  }
</style>
